package com.iflytek.aidemo.student;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.GridLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.util.SessionManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

public class WrongPracticeResultActivity extends AppCompatActivity {
    private ImageView btnBack;
    private TextView tvCorrect;
    private TextView tvTimeUsed;
    private TextView tvSpeed;
    private TextView tvDate;
    private GridLayout questionListContainer;
    private Button btnEnsure;
    private final ApiService apiService = new ApiServiceImpl();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wrong_practice_result);
        btnBack = findViewById(R.id.btn_back);
        tvCorrect = findViewById(R.id.tv_correct_count);
        tvTimeUsed = findViewById(R.id.tv_time_used);
        tvSpeed = findViewById(R.id.tv_speed);
        tvDate = findViewById(R.id.tv_date);
        questionListContainer = findViewById(R.id.question_list_container);
        btnEnsure = findViewById(R.id.btn_ensure);

        btnBack.setOnClickListener(v -> finish());

        int correct = getIntent().getIntExtra("correct_count", 0);
        int total = getIntent().getIntExtra("total_count", 0);
        long elapsed = getIntent().getLongExtra("elapsed_ms", 0L);
        ArrayList<String> questions = getIntent().getStringArrayListExtra("questions");
        ArrayList<String> rightAnswers = getIntent().getStringArrayListExtra("answers");
        ArrayList<String> userAnswers = getIntent().getStringArrayListExtra("user_answers");
        boolean[] correctFlags = getIntent().getBooleanArrayExtra("correct_flags");

        tvCorrect.setText("答对 " + correct + " 题");
        String timeStr = formatDuration(elapsed);
        tvTimeUsed.setText("用时 " + timeStr);
        String speedStr = total > 0 ? String.format(Locale.getDefault(), "%.2f 秒/题", (elapsed / 1000f) / total) : "0 秒/题";
        tvSpeed.setText("速度 " + speedStr);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.getDefault());
        tvDate.setText(sdf.format(new Date()));

        if (questionListContainer != null) {
            questionListContainer.removeAllViews();
            if (questions != null && !questions.isEmpty()) {
                //加载布局文件
                LayoutInflater inflater = LayoutInflater.from(this);
                for (int i = 0; i < questions.size(); i++) {
                    //将答题情况列表与详情卡片展示xml文件联系
                    View row = inflater.inflate(R.layout.item_result_question, questionListContainer, false);
                    TextView tvExpr = row.findViewById(R.id.tv_expression);
                    TextView tvAns = row.findViewById(R.id.tv_answer_value);
                    ImageView ivIcon = row.findViewById(R.id.iv_result_icon);

                    String q = questions.get(i);
                    tvExpr.setText(getStem(q));

                    String userAns = (userAnswers != null && i < userAnswers.size()) ? userAnswers.get(i) : "";
                    String rightAns = (rightAnswers != null && i < rightAnswers.size()) ? rightAnswers.get(i) : "";
                    boolean isCorrect = (correctFlags != null && i < correctFlags.length) ? correctFlags[i] : false;

                    tvAns.setText(userAns != null && userAns.length() > 0 ? userAns : rightAns);
                    ivIcon.setImageResource(isCorrect ? R.drawable.ic_check_circle_green : R.drawable.ic_error_circle_red);

                    GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
                    lp.width = 0;
                    lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    lp.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f);
                    lp.setMargins(dp(6), dp(6), dp(6), dp(6));
                    questionListContainer.addView(row, lp);
                }
            }
        }

        btnEnsure.setOnClickListener(v -> {
            boolean fromPush = getIntent() != null && getIntent().getBooleanExtra("from_push", false);
            if (!fromPush) {
                // 清除待办标记
                WrongPushStore.setPending(this, false);
                // 标记本周已处理
                markWeekAsCleared();
                finish();
                return;
            }

            // 从推送进入：提示是否删除上周练习记录
            new AlertDialog.Builder(this)
                    .setTitle("完成上周练习")
                    .setMessage("是否删除本次（上周）练习的错题记录？")
                    .setPositiveButton("删除", (d, w) -> deleteAndFinish())
                    .setNegativeButton("保留", (d, w) -> {
                        // 标记本周已处理
                        markWeekAsCleared();
                        finish();
                    })
                    .show();
        });
    }

    private void markWeekAsCleared() {
        // 标记本周已处理
        SessionManager sm = new SessionManager(this);
        String uid = sm.getCurrentUser() != null ? sm.getCurrentUser().getUserId() : "0";
        String weekKey = WrongPushStore.currentWeekKey();

        WrongPushStore.markClearedForWeek(this, uid, weekKey, true);

        WrongPushStore.setPending(this, false);

        SharedPreferences sp = getSharedPreferences("wrong_push", MODE_PRIVATE);
        for (Map.Entry<String, ?> entry : sp.getAll().entrySet()) {
            System.out.println("   " + entry.getKey() + " = " + entry.getValue());
        }
        try {
            Intent intent = new Intent("com.iflytek.aidemo.action.UPDATE_RED_DOT");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            System.out.println("7. Local broadcast sent successfully!");
        } catch (Exception e) {
            System.err.println("Error sending local broadcast: " + e.getMessage());
            e.printStackTrace();
            // 回退到普通广播（仅用于调试）
            try {
                Intent intent = new Intent("com.iflytek.aidemo.action.UPDATE_RED_DOT");
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                System.out.println("7. Fallback to global broadcast sent.");
            } catch (Exception ex) {
                System.err.println("Error sending fallback broadcast: " + ex.getMessage());
            }
        }
    }

    private void deleteAndFinish() {
        //ArrayList<Integer> ids = getIntent().getIntegerArrayListExtra("wrong_question_ids");
//        if (ids == null || ids.isEmpty()) {
//            markWeekAsCleared();
//            finish();
//            return;
//        }
        SessionManager sm = new SessionManager(this);
        String userIdStr = sm.getCurrentUser() != null ? sm.getCurrentUser().getUserId() : "0";
        int studentId;
        try { studentId = Integer.parseInt(userIdStr); } catch (Exception e) { studentId = 0; }

        final int sid = studentId;
        new Thread(() -> {
            ApiResponse<Boolean> resp = apiService.completeWrongQuestions(sid);
            runOnUiThread(() -> {
                if (resp != null && resp.getCode() == 200 && Boolean.TRUE.equals(resp.getData())) {
                    Toast.makeText(this, "已删除上周错题记录", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "删除失败，稍后重试", Toast.LENGTH_SHORT).show();
                }
                // 标记本周已处理
                markWeekAsCleared();
                finish();
            });
        }).start();
    }

    private String formatDuration(long ms) {
        long sec = ms / 1000;
        long m = sec / 60;
        long s = sec % 60;
        if (m > 0) {
            return m + "分" + s + "秒";
        } else {
            return s + "秒";
        }
    }

    private String getStem(String q) {
        if (q == null) return "";
        int eq = q.indexOf('=');
        String stem = eq >= 0 ? q.substring(0, eq) : q;
        stem = stem.trim();
        if (stem.endsWith("?")) stem = stem.substring(0, stem.length() - 1).trim();
        return stem;
    }

    private int dp(int d) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round(d * density);
    }
}
